// pages/collection/index.js
Page({
  data: {
    collections: [],
    page: 1,
    loading: false,
    hasMore: true
  },

  onLoad() {
    this.loadCollections()
  },

  // 加载收藏列表
  async loadCollections(refresh = false) {
    if (this.data.loading || (!refresh && !this.data.hasMore)) return

    try {
      this.setData({ loading: true })
      
      const page = refresh ? 1 : this.data.page
      const res = await wx.cloud.callFunction({
        name: 'getCollections',
        data: { page }
      })

      if (res.result.success) {
        const { list, hasMore } = res.result.data
        
        this.setData({
          collections: refresh ? list : [...this.data.collections, ...list],
          page: page + 1,
          hasMore
        })
      } else {
        wx.showToast({
          title: res.result.message || '加载失败',
          icon: 'none'
        })
      }
    } catch (err) {
      console.error('加载收藏列表失败', err)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 点击文章跳转到详情页
  onArticleTap(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/article/detail/index?id=${id}`
    })
  },

  // 取消收藏
  async onCancelCollection(e) {
    const { id } = e.currentTarget.dataset
    
    try {
      const res = await wx.cloud.callFunction({
        name: 'toggleCollection',
        data: { articleId: id }
      })

      if (res.result.success) {
        // 从列表中移除
        const collections = this.data.collections.filter(item => item.articleId !== id)
        this.setData({ collections })
        
        wx.showToast({
          title: '已取消收藏',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: res.result.message || '操作失败',
          icon: 'none'
        })
      }
    } catch (err) {
      console.error('取消收藏失败', err)
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      })
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadCollections(true)
    wx.stopPullDownRefresh()
  },

  // 触底加载更多
  onReachBottom() {
    this.loadCollections()
  }
})